<template>
	<view>
		<view class="bgw" id="topBox">
			<u-line></u-line>
			<u-tabs :list="tabs" :current="tabsCurrent" @click="tabsClick" :activeStyle="tabsActiveStyle" lineColor="#00BF9B">
			</u-tabs>
			<u-line></u-line>
			<u-tabs :list="tabs2" :current="tabsCurrent2" @click="tabsClick2" :activeStyle="tabsActiveStyle"
				lineColor="#00BF9B">
			</u-tabs>
			<u-line></u-line>
		</view>
		
		<nodata v-if="loadingStatus == 'end' && scrollData.length == 0"></nodata>

		<dish-list :data="scrollData" :menu="scrollMenu" :height="scrollHeight" :scroll_id="scrollViewId"
			@updata="scrollUpdata" ref="scrollRef" v-if="scrollData.length>0" :packed="packed_order_record"></dish-list>

		<view class="fixed-bottom-box" id="bottomBox">
			<template v-if="tips">
				<view class="wrapper">
					<u-alert :title="tips" type = "warning"></u-alert>
				</view>
				<view class="blank10"></view>
			</template>
			
			
			<view class="flex u-border-top bgw">
				<view class="bag-btn flex justify-center" @click="openBag">
					<u-badge type="error" :isDot="true" :absolute="true" :offset="[0,0]" v-if="bagList.length>0"></u-badge>
					<u-icon name="bag-fill" size="20" color="#ffffff"></u-icon>
				</view>
				<view class="flex-1" v-if="bagList.length>0">
					<view class="">
						共 <text class="font-bold">{{bagList.length}}</text>种菜品
					</view>
				</view>
				<view class="flex-1" v-else>
					<view class="text-red">
						{{isOvertime?'已超时':'请添加菜品'}}
					</view>
				</view>
				<view class="btn-add-order" @click="save">
					下单
				</view>
			</view>
			
		</view>

		<u-popup :show="popupShow" @close="popupClose" @open="popupOpen" mode="bottom" :closeable="true">
			<view class="flex justify-center" style="background-color: #f5f5f5;height: 44px;">
				<view>
					已添加的菜品
				</view>
			</view>
			<scroll-view scroll-y scroll-with-animation class="popup-scroll">
				<view class="">
					<template v-for="v in bagList">
						<view class="wrapper" v-if="valueObj[v.dish_key_id]>0">
							<view class="blank20"></view>
							<view class="flex">
								<u--image :src="v.image_1920?'data:image/png;base64,'+v.image_1920:''" shape="square" radius="8" width="40"
									height="40"></u--image>
								<view class="flex-1 ml15">
									<view class="text-ellipsis">
										{{v.dish_key_name}}
									</view>
								</view>
								<view class="flex" style="justify-content: flex-end;">
									<view class="">
										<u-number-box v-model="valueObj[v.dish_key_id]" @change="valChange" :min="min" :max="1"
											:name="v.dish_key_id" :asyncChange="true" :disabledInput="true" bgColor="#ffffff"
											@overlimit="overlimit" :buttonSize="20" :showPlus="false">
											<view slot="minus" class="minus">
												<u-icon name="minus" size="12"></u-icon>
											</view>
											<view slot="plus" class="plus">
												<u-icon name="plus" size="12"></u-icon>
											</view>
										</u-number-box>
									</view>
								</view>
							</view>
							<view class="blank20"></view>
							<u-line color="#e6e6e6"></u-line>
						</view>
					</template>
				</view>
			</scroll-view>
			<view class="wrapper" style="background-color: #f5f5f5;">
				<view class="blank20"></view>
				<u-row justify="space-between" gutter="10">
					<u-col span="6">
						<u-button type="info" text="关闭" @click="popupShow = false"></u-button>
					</u-col>
					<u-col span="6">
						<u-button type="primary" :disabled="bagList.length == 0" text="下单" @click="save"></u-button>
					</u-col>
				</u-row>

				<view class="blank20"></view>
			</view>
		</u-popup>
		
		

	</view>
</template>

<script>
	import dishList from "@/components/dish-list/dish-list.vue";
	import nodata from '@/components/nodata.vue';
	import {
		packed_order_dish_data,
		common_create,
		get_ordered_dish_data
	} from '@/common/api.js';
	export default {
		components: {
			dishList,
			nodata
		},
		data() {
			return {
				tabs: [],
				tabs2: [],
				tabsActiveStyle: {
					color: '#00BF9B',
				},
				tabsCurrent: 0,
				tabsCurrent2: 0,
				scrollData: [],
				scrollMenu: [],
				scrollHeight: 0,
				scrollViewId: 0,
				bagList: [],
				valueObj: {},
				popupShow: false,
				min: 0,
				sessionInfo: {},
				phoneInfo: {},
				isLogin: false,
				company_id: '',
				cost_center_id: '',
				cus_loc_id: '',
				cus_group_id: '',
				dinner_type_category_obj: {},
				treeObj: {},
				add_order_id: this.make_add_function(),
				packed_order_record:[],
				loadingStatus:'',
				tips:'',
				isOvertime:false
			}
		},
		computed:{
			
		},
		methods: {
			checkDate(){
				let date = this.tabs[this.tabsCurrent].id;
				let date_time = new Date(date).getTime();
				let now_time = new Date().getTime();		
				if(date == this.today_year_month_day){
					this.isOvertime = true;
					this.tips = '已超过下单时间。'
					return;
				}
				if(date_time < date_time){
					this.isOvertime = true;
					this.tips = '已超过下单时间。'
					return;
				}
				if(date == this.tomorrow_year_month_day){
					let _hour = new Date().getHours();
					if(_hour<18){
						this.tips = '请于今日18:00前下单，超时则不可下单。'
						this.isOvertime = false;
					}else{
						this.tips = '已超过18:00，不可下单。'
						this.isOvertime = true;
					}
					return;
				}
				this.isOvertime = false;
				this.tips = '';
			},
			tabsClick(item) {
				let oldCurrent = this.tabsCurrent;
				this.tabsCurrent = item.index;
				if (this.bagList.length == 0) {
					this.updataTabs2();
					this.updataScrollData();
					this.bagList = [];
					this.valueObj = {};
					return;
				}
				if (oldCurrent != item.index) {
					this.$store.dispatch('modal', {
						content: '切换日期将撤销当前选菜，或先【下单】所选菜品',
						cancelText: '取消切换',
						confirmText: '确定撤销'
					}).then(() => {
						// this.bagList = [];
						this.updataTabs2();
						this.updataScrollData();
						this.bagList = [];
						this.valueObj = {};
					}).catch(() => {
						this.tabsCurrent = oldCurrent; //不生效
						this.$forceUpdate();
					}).finally(() => {

					})
				}
			},
			tabsClick2(item) {
				let oldCurrent = this.tabsCurrent2;
				this.tabsCurrent2 = item.index;
				if (this.bagList.length == 0) {
					this.updataScrollData();
					return;
				}
				if (oldCurrent != item.index) {
					this.$store.dispatch('modal', {
						content: '切换餐别将撤销当前选菜，或先【下单】所选菜品',
						cancelText: '取消切换',
						confirmText: '确定撤销'
					}).then(() => {
						this.updataScrollData();
						this.bagList = [];
						this.valueObj = {};
					}).catch(() => {
						this.tabsCurrent2 = oldCurrent; //不生效
						this.$forceUpdate();
					}).finally(() => {

					})
				}
			},
			openBag() {
				// this.updataBagList();
				this.popupShow = true;
			},
			popupClose() {
				this.popupShow = false;
			},
			popupOpen() {

			},
			scrollUpdata(obj) {
				this.valueObj = obj;
				this.updataBagList();
			},
			updataBagList() {
				let bagList = [];
				this.scrollData.forEach(v => {
					if (this.valueObj[v.dish_key_id] > 0) {
						bagList.push(v)
					}
				})
				this.bagList = bagList;
			},
			// 份数
			valChange(e) {
				// console.log(e);
				this.valueObj[e.name] = e.value;
				this.$forceUpdate();
				this.$refs.scrollRef.updataValueObj(this.valueObj);
				this.updataBagList();
			},
			overlimit(e) {
				// console.log("overlimit");
				// console.log(e);
			},
			save() {
				this.checkDate();
				if(this.isOvertime){
					uni.$u.toast('很抱歉，已超时，不可下单。');
					return;
				}
				this.popupShow = false;
				if (this.bagList.length == 0) {
					uni.$u.toast('请添加菜品');
					return;
				}
				let vals_list = [];
				vals_list = this.bagList.map(v => {
					let item = {
						'company_id': this.company_id,
						'cus_loc_id': this.cus_loc_id,
						'cus_group_id': this.cus_group_id,
						'cost_center_id': this.cost_center_id,
						'date': v.date,
						'dish_key_id': v.dish_key_id,
						'dinner_type_id': v.dinner_type_id,
						'orderer_no': this.phoneInfo.phoneNumber,
						'id': this.add_order_id()
					};
					return item;
				});
				// console.log(vals_list);
				uni.showLoading({
					title: '提交中'
				});
				common_create({
					vals_list,
					'model_name': 'packed_order_record',
				}).then((res) => {
					this.bagList = [];
					this.valueObj = {};
					this.$refs.scrollRef.updataValueObj(this.valueObj);
					this.get_ordered_dish_data();
					this.$store.dispatch('modal', {
						content: '下单成功！您可在订单中查看。',
						cancelText: '知道了',
						confirmText: '去订单'
					}).then(() => {
						this.nav('/pages/order/order', 'switchTab');
					}).catch(() => {

					})
				}).finally(() => {
					uni.hideLoading();
				})
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				let data = {
					'company_id': this.company_id,
					'cus_loc_id': this.cus_loc_id,
					'cus_group_id': this.cus_group_id
				};
				this.loadingStatus = 'loading';
				packed_order_dish_data(data).then((res) => {
					let {
						dinner_type_category,
						pack_lst
					} = res.result;
					this.dinner_type_category_obj = this.toObj(dinner_type_category, 'id');
					let treeObj = {};
					let tabs = [];
					pack_lst.forEach(v => {
						let {
							dinner_type_id,
							date
						} = v;
						if (!treeObj[date]) {
							let [y,m,d] = date.split('-');
							let name = m+'/'+d;
							if(this.today_year_month_day == date){
								name = '今天';
							}
							if(this.tomorrow_year_month_day == date){
								name = '明天';
							}
							tabs.push({
								name:name,
								id:date
							});
							treeObj[date] = {}
						}!treeObj[date][dinner_type_id] && (treeObj[date][dinner_type_id] = []);
						treeObj[date][dinner_type_id].push(v);
					})
					this.treeObj = treeObj;
					this.tabs = tabs;
					let tabsCurrent = tabs.findIndex(v=>v.name == '明天');
					if(tabsCurrent<0){
						tabsCurrent = 0;
					}
					this.tabsCurrent = tabsCurrent;
					this.updataTabs2();
					this.updataScrollData();
					this.bagList = [];
					this.valueObj = {};
				}).catch(() => {
					uni.hideLoading();
				}).finally(() => {
					this.loadingStatus = 'end';
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			updataTabs2() {
				// console.log('updataTabs2');
				let date = this.tabs[this.tabsCurrent].id;
				let tabs2 = [];
				for (let dinner_type_id in this.treeObj[date]) {
					tabs2.push({
						id: dinner_type_id,
						name: this.dinner_type_category_obj[dinner_type_id].name
					})
				}
				this.tabs2 = tabs2;
				this.tabsCurrent2 = 0;
			},
			updataScrollData() {
				this.checkDate();
				let scrollData = [];
				let date = this.tabs[this.tabsCurrent].id;
				let dinner_type_id = this.tabs2[this.tabsCurrent2].id;
				scrollData = JSON.parse(JSON.stringify(this.treeObj[date][dinner_type_id] || []));
				this.scrollData = scrollData;
				this.valueObj = {};
				this.$refs.scrollRef.updataValueObj(this.valueObj);
			},
			get_ordered_dish_data(){
				let data = {
					'company_id': this.company_id,
					'cost_center_id': this.cost_center_id,
					'cus_group_id': this.cus_group_id,
					'cus_loc_id': this.cus_loc_id,
					'orderer_no': this.phoneInfo.phoneNumber,
				};
				get_ordered_dish_data(data).then((res) => {
					this.packed_order_record = res.result.packed_order_record;
				})
			}
		},
		onLoad() {
			try {
				this.sessionInfo = this.$store.getters.get_sessionInfo;
				this.isLogin = this.$store.getters.get_isLogin;
				this.phoneInfo = this.$store.getters.get_phoneInfo;
			} catch (e) {}
			if (!this.sessionInfo.company_id) {
				uni.reLaunch({
					url: '/pages/index/index'
				});
				return;
			}
			if (!this.isLogin) {
				uni.reLaunch({
					url: '/pages/my/my'
				});
				return;
			};
			this.company_id = this.sessionInfo.company_id[0];
			this.cus_loc_id = this.sessionInfo.cus_loc_id[0];
			this.cus_group_id = this.sessionInfo.cus_group_id[0];
			this.cost_center_id = this.sessionInfo.cost_center_id[0];
			this.get_ordered_dish_data();
			this.getData();	
		},
		onShow() {
			try {

			} catch (e) {

			}
		},
		onReady() {
			this.scrollHeight = this.getClineHeight() - 61 - 91;
			// uni.createSelectorQuery().select('#topBox').boundingClientRect(data => {
			// 	let topHeight = data.height;
			// 	uni.createSelectorQuery().select('#bottomBox').boundingClientRect(data => {
			// 		console.log(this.getClineHeight());
			// 		console.log(data.height);
			// 		console.log(topHeight);
			// 		this.scrollHeight = this.getClineHeight() - data.height - topHeight;
			// 	}).exec()
			// }).exec()
		},
	}
</script>

<style lang="scss">
	.btn-add-order {
		background-color: #00BF9B;
		color: #ffffff;
		height: 60px;
		line-height: 60px;
		width: 100px;
		text-align: center;
	}

	.bag-btn {
		position: relative;
		width: 40px;
		height: 40px;
		background-color: #00BF9B;
		border-radius: 50%;
		margin-left: 30upx;
		margin-right: 30upx;
	}

	.popup-scroll {
		max-height: 800upx;
		min-height: 200upx;
	}

	.minus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: rgb(214, 215, 217);
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		@include flex;
		justify-content: center;
		align-items: center;
	}

	.plus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: rgb(214, 215, 217);
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		@include flex;
		justify-content: center;
		align-items: center;
	}
</style>